/******************************************************************************
 * Copyright (C) 2016  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "node/system/thread_WIN32.h"
#include <assert.h>
#include "node/system/runnable.h"

namespace node {
    namespace system {

        thread_impl::thread_impl(void)
                : _id(0)
                , _runnable(0)
                , _handle((uintptr_t)-1L)
        {

        }
        thread_impl::~thread_impl(void)
        {

        }

        bool thread_impl::start_impl(runnable* runnable)
        {
            assert(_handle == (uintptr_t)-1L);
            _runnable = runnable;
            if ((_handle = _beginthreadex(NULL, 0, thread_impl::proc,
                                          this, 0, (unsigned int*)&_id)) != (uintptr_t)-1L) {
                return true;
            }
            return false;
        }
        void thread_impl::join_impl(void)
        {
            assert(_handle != (uintptr_t)-1L);
            if (_handle != (uintptr_t)-1L) {
                ::WaitForSingleObject((HANDLE)_handle, INFINITE);
            }
        }
        bool thread_impl::joinable_impl(void)
        {
            return _handle != (uintptr_t)-1L;
        }
        bool thread_impl::set_priority_impl(int priority)
        {
          return ::SetThreadPriority((HANDLE)_handle, priority) == TRUE;
        }

        unsigned int thread_impl::proc(void *argument)
        {
            assert(argument);
            thread_impl* impl = static_cast<thread_impl*>(argument);
            impl->_runnable->run();
            return 0;
        }

}}
